package com.vf.admin.client.controller;

import cn.hutool.core.util.ObjectUtil;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dto.CommentDto;
import com.vf.admin.client.dto.CommentReplyDto;
import com.vf.admin.client.dto.DynamicDto;
import com.vf.admin.client.param.UpdateDongTaiWebParam;
import com.vf.admin.client.service.*;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.fiwork.util.DateUtils;
import com.vf.admin.miaodong.entity.*;
import com.vf.admin.utils.StringEx;
import com.vf.admin.utils.TimeUtils;
import com.vf.admin.utils.aliyunoss.OssCheckUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import java.util.*;


import static com.vf.admin.client.common.ClientConstants.client_toke;
import static com.vf.admin.common.Constants.*;
import static com.vf.admin.utils.StringEx.isNull;
import static com.vf.admin.utils.sensitiveword.minganci.sensitiveWordDetection;

/**
 * @author anxiang
 * @version 1.0.0
 * @ClassName AppDongtaiController.java
 * @Description 动态
 * @createTime 2021年07月21日 10:58:0
 */
@CrossOrigin
@Controller
@RequestMapping("/app/dongtai")
public class AppDongtaiController extends ClientBaseController {
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppSetupService appSetupService;
    @Autowired
    AppDynamicService appDynamicService;
    @Autowired
    AppDynamicDianzanService appDynamicDianzanService;
    @Autowired
    AppCommentDianzanService appCommentDianzanService;
    @Autowired
    AppCommentService appCommentService;
    @Autowired
    AppFollowService appFollowService;
    @Autowired
    AppCommentReplyService appCommentReplyService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AppUserDongtaiService appUserDongtaiService;
    @Autowired
    private AppDailyTasController appDailyTasController;
    @Autowired
    AppUserDressupService appUserDressupService;
    @Autowired
    MessageChatFromService messageChatFromService;
    @Autowired
    LovelyGodLogService lovelyGodLogService;
    @Autowired
    AppBeckoningService appBeckoningService;
    @Autowired
    DynamicAlertService dynamicAlertService;
    @Autowired
    SystemAlertService systemAlertService;


    /**
     * 手动修改朋友圈
     */
    @PostMapping(value = "/updateDongTaiWeb")
    @ResponseBody
    public Result updateDongTaiWeb(@RequestBody UpdateDongTaiWebParam param) {
        //取出userIds
        String[] split = param.getUserIds().split(",");
        List<String> userIdList = Arrays.asList(split);
        boolean b = appDynamicService.updateDynamic(userIdList, param.getTime(), param.getAddress());
        if (b) {
            return this.sucessJSON("操作成功");
        }
        return this.errorJSON("操作失败");
    }


    /**
     * 手动修改朋友圈数据
     */
    @RequestMapping(value = "/updateDongTai", method = RequestMethod.POST)
    @ResponseBody
    public Result updateDongTai(String userIds, String time, String address) {
        //取出userIds
        String[] split = userIds.split(",");
        List<String> userIdList = Arrays.asList(split);
        boolean b = appDynamicService.updateDynamic(userIdList, time, address);
        if (b) {
            return this.sucessJSON("操作成功");
        }
        return this.errorJSON("操作失败");
    }


    @RequestMapping(value = "/updateDongTaiNow", method = RequestMethod.POST)
    @ResponseBody
    public Result updateDongTaiNow(String userIds) {
        //取出userIds
        String[] split = userIds.split(",");
        List<String> userIdList = Arrays.asList(split);
        boolean b = appDynamicService.updateDongTaiNow(userIdList);
        if (b) {
            return this.sucessJSON("操作成功");
        }
        return this.errorJSON("操作失败");
    }

    /**
     * @param message 动态内容
     * @param media   动态图片  支持多张/单张
     * @param lon     lon  经度
     * @param lat     lat  维度
     * @param city    city  城市
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 发布动态
     */
    @RequestMapping(value = "/addDongtaiVersion2", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result addDongtaiVersion2(HttpServletRequest request,
                                     String message,
                                     String media,
                                     String lon,
                                     String lat,
                                     String city,
                                     Integer type) {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);

            if (isNull(message)) {
                return errorJSON("动态内容不能为空");
            }
            if (message.toLowerCase().contains("script")) {
                return this.errorJSON("请不要非法攻击");
            }
            if (message.trim().length() > dongtai_length) {
                return this.errorJSON("动态内容最多" + dongtai_length + "字");
            }
            for (Object object : Constants.jsonArray) {
                if (message.contains(object.toString())) {
                    return this.errorJSON("内容不能包含敏感词");
                }
            }
            //动态发布保存
            appDynamicService.dongtaiSave(
                    message, media,
                    lon, lat, city,
                    user.getId(), user.getPic(),
                    user.getNick(), user.getLoginname(),
                    user.getSex(), type);
//            //增加动态数量
//            appUserService.dongtaiallUpdate(userId, zengjia);
//            //增加新增动态数量
//            appUserService.dongtaiNewUpdate(userId);
//
//            appDailyTasController.getAwardEveryDay(userId, ClientConstants.TaskEveryDay.SEND_DYNAMIC);

            return sucessJSON("成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }


    /**
     * @param message 动态内容
     * @param image   动态图片  支持多张/单张
     * @param image   lon  经度
     * @param image   lat  维度
     * @param image   city  城市
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 发布动态
     */
    @RequestMapping(value = "/addDongtai", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result addDongtai(HttpServletRequest request, String message, MultipartFile[] image, String lon, String lat, String city, Integer type) {
        try {
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);

            if (isNull(message)) {
                return errorJSON("动态内容不能为空");
            }
            if (message.toLowerCase().contains("script")) {
                return this.errorJSON("请不要非法攻击");
            }
            if (sensitiveWordDetection(message, Constants.keyWordSet)) {
                return this.errorJSON("内容不能包含敏感词");
            }
            if (message.trim().length() > dongtai_length) {
                return this.errorJSON("动态内容最多" + dongtai_length + "字");
            }
            for (Object object : Constants.jsonArray) {
                if (message.contains(object.toString())) {
                    return this.errorJSON("内容不能包含敏感词BBB");

                }
            }
            String images = "";
            //判断是否上传动态图片
            if (image != null && image.length > 0) {
                //上传：循环获取file数组中得文件
                StringBuffer stringBuffer = new StringBuffer();
                for (int i = 0; i < image.length; i++) {
                    MultipartFile files = image[i];
                    if (!files.isEmpty()) {
                        //判断图片大小
                        if (files.getSize() <= 1073741824) {

                            String filesName = files.getOriginalFilename();
                            String suffix = filesName.substring(filesName.indexOf("."));
                            if (checkMediaType(suffix)) {
                                //上传阿里云oss
                                String ossUrl = appUserService.aliyunOssupload(files);
                                if (isNull(ossUrl)) {
                                    return this.errorJSON("视频上传失败");
                                }
                                //拼接
                                stringBuffer.append(ossUrl + ",");
                            } else {
                                //上传阿里云oss
                                String ossUrl = appUserService.aliyunOssupload(files);
                                if (isNull(ossUrl)) {
                                    return this.errorJSON("图片上传失败");
                                }
                                //拼接
                                stringBuffer.append(ossUrl + ",");
                                boolean b = OssCheckUtils.imageSyncCheckV2(ossUrl);
                                if (!b) {
                                    return this.errorJSON("发布内容违规");
                                }
                            }
                        } else {
                            return this.errorJSON("大小超出限制");
                        }
                    }
                }
                //保存图片拼接路径
                images = stringBuffer.toString();
            }
            //动态发布保存
            appDynamicService.dongtaiSave(message, images, lon, lat, city, user.getId(), user.getPic(), user.getNick(), user.getLoginname(), user.getSex(), type);
            //增加动态数量
            appUserService.dongtaiallUpdate(userId, zengjia);
            //增加新增动态数量
            appUserService.dongtaiNewUpdate(userId);

            appDailyTasController.getAwardEveryDay(userId, ClientConstants.TaskEveryDay.SEND_DYNAMIC);
            return sucessJSON("成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }

    /**
     * 判断视频格式是否正确
     *
     * @Param: [fileEnd 文件后缀]
     * @return: boolean
     * @Author: zhouyunyi
     * @Date: 2021/07/22
     * @Time: 16:41
     */
    private boolean checkMediaType(String fileEnd) {
        String[] suffixFile = {".mp4", ".3gp", ".avi", ".rm", ".mov", ".rmvb", ".flv", ".hevc"};
        Iterator<String> type = Arrays.asList(suffixFile).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileEnd.equals(ext)) {
                return true;
            }
        }
        return false;
    }


//    /**
//     * @param message 动态内容
//     * @param image   动态图片  支持多张/单张
//     * @param image   lon  经度
//     * @param image   lat  维度
//     * @param image   city  城市
//     * @return com.vf.admin.common.entity.Result
//     * @author anxiang
//     * @Description 发布动态
//     */
//    @RequestMapping(value = "/addDongtai", method = RequestMethod.POST)
//    @ResponseBody
//    @Transactional(rollbackFor = Exception.class)
//    public Result addDongtai(HttpServletRequest request, String message, MultipartFile[] image, MultipartFile[] viedo,String lon, String lat, String city) {
//        try {
//            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
//            //获取当前登录用户的user对象
//            AppUser user = appUserService.get(userId);
//
//            if (isNull(message)) {
//                return errorJSON("动态内容不能为空");
//            }
//            if (message.toLowerCase().contains("script")) {
//                return this.errorJSON("请不要非法攻击");
//            }
//            if (sensitiveWordDetection(message, Constants.keyWordSet)) {
//                return this.errorJSON("内容不能包含敏感词");
//            }
//            if (message.trim().length() > dongtai_length) {
//                return this.errorJSON("动态内容最多" + dongtai_length + "字");
//            }
//            for (Object object : Constants.jsonArray) {
//                if (message.contains(object.toString())) {
//                    return this.errorJSON("内容不能包含敏感词BBB");
//
//                }
//            }
//            String images = "";
//            //判断是否上传动态图片
//            if (image != null && image.length > 0) {
//                //上传：循环获取file数组中得文件
//                StringBuffer stringBuffer = new StringBuffer();
//                for (int i = 0; i < image.length; i++) {
//                    MultipartFile files = image[i];
//                    if (!files.isEmpty()) {
//                        //判断图片大小
//                        if (files.getSize() <= 1073741824) {
//                            //上传阿里云oss
//                            String ossUrl = appUserService.aliyunOssupload(files);
//                            if (isNull(ossUrl)) {
//                                return this.errorJSON("图片上传失败");
//                            }
//                            //拼接
//                            stringBuffer.append(ossUrl + ",");
//                            boolean b = OssCheckUtils.imageSyncCheckV2(ossUrl);
//                            if (!b) {
//                                return this.errorJSON("发布内容违规");
//                            }
//                        } else {
//                            return this.errorJSON("图片大小超出限制");
//                        }
//                    }
//                }
//                //保存图片拼接路径
//                images = stringBuffer.toString();
//            }
//            //动态发布保存
//            appDynamicService.dongtaiSave(message, images, lon, lat, city, user.getId(), user.getPic(), user.getNick(), user.getLoginname(), user.getSex());
//            //增加动态数量
//            appUserService.dongtaiallUpdate(userId, zengjia);
//            //增加新增动态数量
//            appUserService.dongtaiNewUpdate(userId);
//
//            appDailyTasController.getAwardEveryDay(userId, ClientConstants.TaskEveryDay.SEND_DYNAMIC);
//            return sucessJSON("成功");
//        } catch (Exception e) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return this.errorJSON("网络繁忙，请稍后重试");
//        }
//    }

//    /**
//     * @param message 动态内容
//     * @param image   动态图片  支持多张/单张
//     * @param image   lon  经度
//     * @param image   lat  维度
//     * @param image   city  城市
//     * @return com.vf.admin.common.entity.Result
//     * @author anxiang
//     * @Description 发布动态
//     */
//    @RequestMapping(value = "/sendDongtai", method = RequestMethod.POST)
//    @ResponseBody
//    @Transactional(rollbackFor = Exception.class)
//    public Result sendDongtai(HttpServletRequest request, String message, MultipartFile[] image, String lon, String lat, String city) {
//        try {
//            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
//            //获取当前登录用户的user对象
//            AppUser user = appUserService.get(userId);
//
//            if (isNull(message)) {
//                return errorJSON("动态内容不能为空");
//            }
//            if (message.toLowerCase().contains("script")) {
//                return this.errorJSON("请不要非法攻击");
//            }
//            if (sensitiveWordDetection(message, Constants.keyWordSet)) {
//                return this.errorJSON("内容不能包含敏感词");
//            }
//            if (message.trim().length() > dongtai_length) {
//                return this.errorJSON("动态内容最多" + dongtai_length + "字");
//            }
//            for (Object object : Constants.jsonArray) {
//                if (message.contains(object.toString())) {
//                    return this.errorJSON("内容不能包含敏感词BBB");
//
//                }
//            }
//            String images = "";
//            //判断是否上传动态图片
//            if (image != null && image.length > 0) {
//                //上传：循环获取file数组中得文件
//                StringBuffer stringBuffer = new StringBuffer();
//                for (int i = 0; i < image.length; i++) {
//                    MultipartFile files = image[i];
//                    if (!files.isEmpty()) {
//                        //判断图片大小
//                        if (files.getSize() <= 1073741824) {
//                            //上传阿里云oss
//                            String ossUrl = appUserService.aliyunOssupload(files);
//                            if (isNull(ossUrl)) {
//                                return this.errorJSON("图片上传失败");
//                            }
//                            //拼接
//                            stringBuffer.append(ossUrl + ",");
//                            boolean b = OssCheckUtils.imageSyncCheckV2(ossUrl);
//                            if (!b) {
//                                return this.errorJSON("发布内容违规");
//                            }
//                        } else {
//                            return this.errorJSON("图片大小超出限制");
//                        }
//                    }
//                }
//                //保存图片拼接路径
//                images = stringBuffer.toString();
//            }
//            //动态发布保存
//            appDynamicService.dongtaiSave(message, images, lon, lat, city, user.getId(), user.getPic(), user.getNick(), user.getLoginname(), user.getSex());
//            //增加动态数量
//            appUserService.dongtaiallUpdate(userId, zengjia);
//            //增加新增动态数量
//            appUserService.dongtaiNewUpdate(userId);
//
//            appDailyTasController.getAwardEveryDay(userId, ClientConstants.TaskEveryDay.SEND_DYNAMIC);
//            return sucessJSON("成功");
//        } catch (Exception e) {
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return this.errorJSON("网络繁忙，请稍后重试");
//        }
//    }

    /**
     * 后台发送动态图片
     */
    @ResponseBody
    @RequestMapping("/afterDongtaiUpOssImg")
    public Result upOssImg(MultipartFile[] file) {
        String images = "";
        //判断是否上传动态图片
        if (file != null && file.length > 0) {
            //上传：循环获取file数组中得文件
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < file.length; i++) {
                MultipartFile files = file[i];
                if (!files.isEmpty()) {
                    //判断图片大小
                    if (files.getSize() <= 1073741824) {
                        //上传阿里云oss
                        String ossUrl = appUserService.aliyunOssupload(files);
                        if (isNull(ossUrl)) {
                            return this.errorJSON("图片上传失败");
                        }
                        //拼接
                        stringBuffer.append(ossUrl);
                        boolean b = OssCheckUtils.imageSyncCheckV2(ossUrl);
                        if (!b) {
                            return this.errorJSON("发布内容违规");
                        }
                    } else {
                        return this.errorJSON("图片大小超出限制");
                    }
                }
            }
            //保存图片拼接路径
            images = stringBuffer.toString();
        }
        Map<String, String> mm = new HashMap<>();
        mm.put("name", images);
        mm.put("imgname", "");
        return this.sucessJSON(mm, "保存成功");
    }

    /**
     * 后台发送朋友圈
     */
    @RequestMapping(value = "/afterSendDongtai", method = RequestMethod.POST)
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result sendDongtai(Integer userId, String message, String image, String lon, String lat, String city, Integer type) {
        try {
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);
            //动态发布保存
            appDynamicService.dongtaiSave(message, image, lon, lat, city, user.getId(), user.getPic(), user.getNick(), user.getLoginname(), user.getSex(), type);
            //增加动态数量
            appUserService.dongtaiallUpdate(userId, zengjia);
            //增加新增动态数量
            appUserService.dongtaiNewUpdate(userId);

            appDailyTasController.getAwardEveryDay(userId, ClientConstants.TaskEveryDay.SEND_DYNAMIC);
            return sucessJSON("成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }


    /**
     * @param dongtaiId 动态id
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 获取动态详情
     */
    @RequestMapping(value = "/getDongtaiDetail", method = RequestMethod.POST)
    @ResponseBody
    public Result getDongtaiDetail(HttpServletRequest request, Integer dongtaiId) {
        try {
            if (isNull(dongtaiId)) {
                return errorJSON("ID不能为空");
            }
            //根据动态id获取动态详情
            AppDynamic dynamic = appDynamicService.getByid(dongtaiId);
            if (StringUtils.isEmpty(dynamic)) {
                return errorJSON("动态不存在");
            }
            if (dynamic.getStatus() != 1) {
                return errorJSON("已删除");
            }
            //信息转移Dto
            DynamicDto dd = new DynamicDto();
            BeanUtils.copyProperties(dynamic, dd);
            //判断动态图片是否为空
            if (!isNull(dd.getImage())) {
                //不为空  切割
                String[] arr = dd.getImage().split(",");
                //移入数组
                dd.setImageList(Arrays.asList(arr));
            } else {
                //为空  数组则为空
                dd.setImageList(Arrays.asList());
            }
            //判断用户是否登录
            if (isNull(request.getHeader(client_toke))) {
                //未登录  未点赞
                dd.setDzstate(2);
                dd.setGuanzhuState(2);

            } else {
                Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
                //获取当前登录用户的user对象
                AppUser user = appUserService.get(userId);
                AppUser dynamicUser = appUserService.get(dynamic.getUserid());
                //根据用户id和动态id查询是否已经点赞
                AppDynamicDianzan dianzan = appDynamicDianzanService.getSpecifiedLike(user.getId(), dynamic.getId());
                if (!StringUtils.isEmpty(dianzan)) {
                    //点赞
                    dd.setDzstate(1);
                } else {
                    //未查询到记录  未点赞
                    dd.setDzstate(2);
                }
                //根据用户id和动态发布人userid查询是否已经关注
                AppFollow follow = appFollowService.getFollew(user.getId(), dynamic.getUserid());
                if (!StringUtils.isEmpty(follow)) {
                    //已关注
                    dd.setGuanzhuState(1);
                } else {
                    //未查询到记录  未关注
                    dd.setGuanzhuState(2);
                }

                if (dynamicUser.getIsguizu() == 1) {
                    //是贵族
                    //根据贵族id  获取贵族图标
                    String medal = guizuCacheMap.get(dynamicUser.getNobleid());
                    dd.setMedal(medal);
                } else {
                    dd.setMedal("");
                }

                Map<Integer, Integer> toushiMap = new HashMap<>(16);
                List<AppUserDressup> userDressups = appUserDressupService.getPiliang(String.valueOf(dynamic.getUserid()), 2);
                for (AppUserDressup userDressup : userDressups) {
                    if (userDressup.getState() == 1) {
                        toushiMap.put(userDressup.getUserid(), userDressup.getMountsid());
                    }
                }

                //判断是否设置过头饰
                if (toushiMap.containsKey(dynamic.getUserid())) {
                    //存在则放入
                    dd.setToushi(Constants.toushiCacheMap.get(toushiMap.get(dynamic.getUserid())));
                } else {
                    //不存在则表示未点赞
                    dd.setToushi("");
                }
                AppUser appUser = appUserService.get(dynamic.getUserid());
                dd.setTengxuncode(appUser.getTengxuncode());

                if (redisUtil.hasKey(RedisKeys.BECKONING + user.getId() + "-" + dynamic.getUserid())) {
                    dd.setIsBeckoning(1);
                } else {
                    dd.setIsBeckoning(2);
                }
                if (appUser.getVipEndDate() != null) {
                    dd.setIsVip(TimeUtils.afterNow(appUser.getVipEndDate())? 1: 0);
                }
            }
            int count = appCommentService.plcount(dynamic.getId());
            dd.setPlcount(count);
            return this.sucessJSON(dd);
        } catch (Exception e) {
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }


    /**
     * @param dongtaiId 动态id
     * @param pageNo    页码
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 查看某个动态的评论列表
     */
    @RequestMapping(value = "/getDpinglunList", method = RequestMethod.POST)
    @ResponseBody
    public Result getDpinglunList(HttpServletRequest request, Integer dongtaiId, Integer pageNo) {
        try {
            if (isNull(dongtaiId)) {
                return errorJSON("ID不能为空");
            }
            if (pageNo == null || pageNo <= 0) {
                return this.errorJSON("暂未数据");
            }

            //查询指定动态&正常的评论数据
            SplitPageBean splitPage = new SplitPageBean(pageNo, 20);
            List<AppComment> commentList = appCommentService.specificUserList(dongtaiId, splitPage);
            List<CommentDto> list = new ArrayList<>();
            boolean flag = false;
            AppUser user = new AppUser();
            //判断用户是否登录
            if (!isNull(request.getHeader(client_toke))) {
                //获取最新数据
                Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
                //获取当前登录用户的user对象
                user = appUserService.get(userId);
                flag = true;
            }
            //判断数据是否为空
            if (commentList != null && commentList.size() > 0) {
                //遍历动态list
                for (AppComment comment : commentList) {
                    //信息转移Dto
                    CommentDto cd = new CommentDto();
                    BeanUtils.copyProperties(comment, cd);
                    if (flag) {
                        //根据用户id和动态id查询是否已经点赞
                        AppCommentDianzan dianzan = appCommentDianzanService.getSpecifiedLike(user.getId(), comment.getId());
                        if (!StringUtils.isEmpty(dianzan)) {
                            //点赞
                            cd.setDzstate(1);
                        } else {
                            //未查询到记录  未点赞
                            cd.setDzstate(2);
                        }
                    } else {
                        cd.setDzstate(2);
                    }
                    //获取回复总数量
                    List<AppCommentReply> commentReplyList = appCommentReplyService.hfcount(comment.getId());
                    cd.setHfcount(commentReplyList.size());
                    List<Object> hfList = new ArrayList<>();
                    if (commentReplyList.size() > 0) {
                        int lenfth = commentReplyList.size() >= 3 ? 3 : commentReplyList.size();
                        System.out.println("长度：" + lenfth);
                        for (int i = 0; i < lenfth; i++) {
                            Map<String, Object> map = new HashMap<>(16);
                            map.put("hfpic", commentReplyList.get(i).getPic());
                            map.put("hfnick", commentReplyList.get(i).getNick());
                            map.put("hfphone", commentReplyList.get(i).getPhone());
                            map.put("hfneirong", commentReplyList.get(i).getNeirong());
                            hfList.add(map);
                        }
                    }
                    cd.setHfList(hfList);

                    AppUser appUser = appUserService.get(cd.getUserid());
                    if (appUser != null) {
                        cd.setIsVip(TimeUtils.afterNow(appUser.getVipEndDate())? 1: 0);
                    }
                    //移入list
                    list.add(cd);
                }
                return this.sucessPage(list, splitPage.getNextPageNo());
            } else {
                return this.sucessPage(list, -1);
            }
        } catch (Exception e) {
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }

    /**
     * @param dongtaiId 动态id
     * @param type      操作状态   1点赞  2取消点赞
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 动态点赞/取消点赞
     */
    @RequestMapping(value = "/updateDongtaiLike", method = RequestMethod.POST)
    @ResponseBody
    public Result updateDongtaiLike(HttpServletRequest request, Integer dongtaiId, Integer type) {
        try {
            if (isNull(dongtaiId)) {
                return errorJSON("ID不能为空");
            }
            if (isNull(type)) {
                return errorJSON("类型错误");
            }
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);
            //根据动态id获取动态详情
            AppDynamic dynamic = appDynamicService.getByid(dongtaiId);
            if (StringUtils.isEmpty(dynamic)) {
                return errorJSON("动态不存在");
            }
            if (dynamic.getStatus() != 1) {
                return errorJSON("已删除");
            }
            AppUser appUser = appUserService.get(dynamic.getUserid());
            String dynamicFirstImage = null;
            if (org.apache.commons.lang3.StringUtils.isNotBlank(dynamic.getImage())) {
                String[] split = dynamic.getImage().split(",");
                dynamicFirstImage = split[0];
            }

            //获取指定用户&指定动态获取点赞信息
            AppDynamicDianzan dianzan = appDynamicDianzanService.getSpecifiedLike(user.getId(), dongtaiId);
            if (type == 1) {
                if (StringUtils.isEmpty(dianzan)) {
                    //动态点赞保存
                    appDynamicDianzanService.dynamicSave(dongtaiId, user.getNick(), user.getPic(), user.getLoginname(), user.getId());
                    //变更动态点赞数量
                    appDynamicService.dianzanNumUpdate(dynamic.getId(), 1);

                    String key = String.format(RedisKeys.PARSE_DYNAMIC_USER, dongtaiId, userId);
                    Object o_value = redisUtil.get(key);
                    //首次点赞给被点赞者增加魅力值
                    if (o_value == null) {
                        AppSetup setup = appSetupService.get();
                        redisUtil.set(key, 1, DateUtils.calculateCurrentTime2SecondDaySec());

                        //判断被点赞用户今日获取魅力值次数上限
                        key = String.format(RedisKeys.DYNAMIC_PARSE_FOR, dynamic.getUserid());
                        o_value = redisUtil.get(key);
                        if (o_value == null) {
                            appUserService.addCharm(dynamic.getUserid(), setup.getDynamicParseCharmGrowth(), "动态被点赞");
                        } else {
                            Integer count = Integer.valueOf(o_value.toString());
                            if (count.compareTo(setup.getDynamicParseEveryDayMax()) == -1) {
                                appUserService.addCharm(dynamic.getUserid(), setup.getDynamicParseCharmGrowth(), "动态被点赞");
                            }
                        }
                    }
                    //发送聊天消息
                    appDynamicService.sendDynamicHello(user, appUser, dynamic.getId(), dynamicFirstImage, "你好呀~你的动态很赞！");
                    //添加动态通知
                    dynamicAlertService.add(userId, dynamic.getUserid(), dynamic.getId(), dynamicFirstImage, ClientConstants.DynamicAlert.PARSE_DYNAMIC, null);
                    //发送小秘书消息
                    systemAlertService.parseDynamic(appUser.getTengxuncode(), user.getNick());
                    return sucessJSON((dynamic.getGivenum() + 1), "成功");
                } else {
                    return errorJSON("已点赞");
                }
            } else if (type == dtpl_quxiao) {
                if (!StringUtils.isEmpty(dianzan)) {
                    //删除点赞信息
                    appDynamicDianzanService.del(dianzan.getId());
                    //变更动态点赞数量
                    appDynamicService.dianzanNumUpdate(dynamic.getId(), 2);

                    dynamicAlertService.delParseDynamic(userId, dynamic.getUserid(), dynamic.getId());
                    return sucessJSON((dynamic.getGivenum() - 1), "取消点赞成功");
                } else {
                    return errorJSON("您当前未点赞");
                }
            } else {
                return errorJSON("参数错误");
            }
        } catch (Exception e) {
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }


    /**
     * @param commentid 评论id
     * @param type      操作状态   1点赞  2取消点赞
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 评论点赞/取消点赞
     */
    @RequestMapping(value = "/updatePinglunLike", method = RequestMethod.POST)
    @ResponseBody
    public Result updatePinglunLike(HttpServletRequest request, Integer commentid, Integer type) {
        try {
            if (isNull(commentid)) {
                return errorJSON("ID不能为空");
            }
            if (isNull(type)) {
                return errorJSON("类型错误");
            }

            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);

            //根据动态id获取动态详情
            AppComment comment = appCommentService.getId(commentid);
            if (StringUtils.isEmpty(comment)) {
                return errorJSON("内容不存在");
            }
            if (comment.getStatus() != 1) {
                return errorJSON("已删除");
            }
            AppCommentDianzan dianzan = appCommentDianzanService.getSpecifiedLike(user.getId(), commentid);
            if (type == 1) {
                if (StringUtils.isEmpty(dianzan)) {
                    //增加评论点赞数量
                    appCommentService.updateZanNum(commentid, 1);
                    //评论点赞保存
                    appCommentDianzanService.commentDianzanSave(commentid, user.getNick(), user.getPic(), user.getLoginname(), user.getId());

                    //添加动态通知
                    AppDynamic dynamic = appDynamicService.getByid(comment.getDynamicid());
                    String dynamicImage = null;
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(dynamic.getImage())) {
                        String[] split = dynamic.getImage().split(",");
                        dynamicImage = split[0];
                    }
                    dynamicAlertService.add(userId, comment.getUserid(), dynamic.getId(), dynamicImage, ClientConstants.DynamicAlert.PARSE_COMMEND, null);
                    return sucessJSON("成功");
                } else {
                    return errorJSON("已点赞");
                }
            } else if (type == dtpl_quxiao) {
                if (!StringUtils.isEmpty(dianzan)) {
                    //减少评论点赞数量
                    appCommentService.updateZanNum(commentid, 2);
                    //评论点赞信息删除
                    appCommentDianzanService.del(dianzan.getId());

                    dynamicAlertService.delParseComment(userId, comment.getUserid(), comment.getDynamicid());
                    return sucessJSON("取消点赞成功");
                } else {
                    return errorJSON("您当前未点赞");
                }
            } else {
                return errorJSON("not support");
            }
        } catch (Exception e) {
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }


    /**
     * @param dongtaiId 动态ID
     * @param message   评论内容
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 对动态进行评论
     */
    @RequestMapping(value = "/dynamicallyComment", method = RequestMethod.POST)
    @ResponseBody
    public Result dynamicallyComment(HttpServletRequest request, Integer dongtaiId, String message) {
        try {
            if (isNull(dongtaiId)) {
                return errorJSON("ID不能为空");
            }
            if (isNull(message)) {
                return errorJSON("内容不能为空");
            }
            if (sensitiveWordDetection(message, Constants.keyWordSet)) {
                return this.errorJSON("不能包含敏感词");
            }
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);

            //根据动态id获取动态详情
            AppDynamic dynamic = appDynamicService.getByid(dongtaiId);
            if (StringUtils.isEmpty(dynamic)) {
                return errorJSON("动态不存在");
            }
            if (dynamic.getStatus() != 1) {
                return errorJSON("动态已删除");
            }
            AppUser appUser = appUserService.get(dynamic.getUserid());
            String dynamicFirstImage = null;
            if (org.apache.commons.lang3.StringUtils.isNotBlank(dynamic.getImage())) {
                String[] split = dynamic.getImage().split(",");
                dynamicFirstImage = split[0];
            }
            //评论发布保存
            appCommentService.pinglunSave(dongtaiId, message, user.getSex(), user.getNick(), user.getPic(), user.getLoginname(), user.getId());
            //变更动态评论数量
            appDynamicService.pinglunNumUpdate(dynamic.getId(), 1);

            appDailyTasController.getAwardDynamicCommentOnce(userId, ClientConstants.TaskOnce.DYNAMIC_COMMEND);
            //发送聊天消息
            appDynamicService.sendDynamicHello(user, appUser, dynamic.getId(), dynamicFirstImage, "嗨~我刚刚评论了你的动态~");
            //添加动态通知
            dynamicAlertService.add(userId, dynamic.getUserid(), dynamic.getId(), dynamicFirstImage, ClientConstants.DynamicAlert.COMMEND_DYNAMIC, message);
            //发送小秘书消息
            if (!appUser.getId().equals(user.getId())) {
                systemAlertService.commendDynamic(appUser.getTengxuncode(), user.getNick());
            }
            return sucessJSON("成功");
        } catch (Exception e) {
            return this.errorJSON("网络繁忙，请稍后重试");
        }
    }


    /**
     * @param commentid 评论id
     * @param message   评论内容
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 对评论进行回复
     */
    @RequestMapping(value = "/replyToComments", method = RequestMethod.POST)
    @ResponseBody
    public Result replyToComments(HttpServletRequest request, Integer commentid, String message) {
        try {
            if (isNull(commentid)) {
                return errorJSON("Id cannot be empty");
            }
            if (isNull(message)) {
                return errorJSON("Comment content cannot be empty");
            }
            if (sensitiveWordDetection(message, Constants.keyWordSet)) {
                return this.errorJSON("Comment content contains sensitive words!");
            }
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);
            //根据评论id获取评论详情
            AppComment comment = appCommentService.getId(commentid);
            if (StringUtils.isEmpty(comment)) {
                return errorJSON("Comment does not exist");
            }
            if (comment.getStatus() != 1) {
                return errorJSON("Comment deleted");
            }
            AppUser pluser = appUserService.get(comment.getUserid());
            //评论回复保存
            appCommentReplyService.plHuifuSave(commentid, user, pluser, message);

            //添加动态通知
            AppDynamic dynamic = appDynamicService.getByid(comment.getDynamicid());
            String dynamicImage = null;
            if (org.apache.commons.lang3.StringUtils.isNotBlank(dynamic.getImage())) {
                String[] split = dynamic.getImage().split(",");
                dynamicImage = split[0];
            }
            dynamicAlertService.add(userId, comment.getUserid(), dynamic.getId(), dynamicImage, ClientConstants.DynamicAlert.REPLY_COMMENT, message);
            return sucessJSON("成功");
        } catch (Exception e) {
            e.printStackTrace();
            return this.errorJSON("The system is busy,please try again later");
        }
    }

    /**
     * 删除个人动态
     *
     * @Param: [id 动态id]
     * @return: com.vf.admin.common.entity.Result
     * @Author: zhouyunyi
     * @Date: 2021/07/29
     * @Time: 11:44
     */
    @RequestMapping("/delDongtai")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result delDongtai(Integer id) {
        try {
            if (StringEx.isNull(id)) {
                return this.errorJSON("No dynamic information found");
            }
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
            //获取当前登录用户的user对象
            AppUser user = appUserService.get(userId);
            //删除动态（只改动态）
            AppDynamic dynamic = appDynamicService.getByid(id);
            if (StringUtils.isEmpty(dynamic)) {
                return this.errorJSON("Dynamic does not exist");
            }
            if (!dynamic.getUserid().equals(user.getId())) {
                return this.errorJSON("You cannot delete this activity");
            }
            appDynamicService.delDongtai(id);
            //减少用户动态总数
            appUserService.dongtaiallUpdate(user.getId(), jianshao);
            return this.sucessJSON("成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return this.errorJSON("The system is busy,please try again later");
        }
    }

    /**
     * @param commentid 评论id
     * @param pageNo    页码
     * @return com.vf.admin.common.entity.Result
     * @author anxiang
     * @Description 查看某个评论的回复列表
     */
    @RequestMapping(value = "/getDhuifuList", method = RequestMethod.POST)
    @ResponseBody
    public Result getDhuifuList(HttpServletRequest request, Integer commentid, Integer pageNo) {
        try {
            if (isNull(commentid)) {
                return errorJSON("Id cannot be empty");
            }
            if (pageNo == null || pageNo <= 0) {
                return this.errorJSON("No more data！");
            }
            AppComment comment2 = appCommentService.getId(commentid);
            if (StringUtils.isEmpty(comment2)) {
                return this.errorJSON("Comment does not exist");
            }
            //查询指定评论&正常的回复数据
            SplitPageBean splitPage = new SplitPageBean(pageNo, 20);
            List<AppCommentReply> huifuList = appCommentReplyService.specificUserList(commentid, splitPage);
            List<CommentReplyDto> list = new ArrayList<>();
            boolean flag = false;
            AppUser user = new AppUser();
            Map<String, Object> toMap = new HashMap<>(16);
            toMap.put("pl", comment2.getNeirong());
            toMap.put("plname", comment2.getNick());
            toMap.put("plimg", comment2.getPic());
            toMap.put("plsex", comment2.getSex());
            if (!isNull(request.getHeader(client_toke))) {
                //获取最新数据
                Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
                //获取当前登录用户的user对象
                user = appUserService.get(userId);
                flag = true;
            }
            if (flag) {
                //根据用户id和动态id查询是否已经点赞
                AppCommentDianzan dianzan = appCommentDianzanService.getSpecifiedLike(user.getId(), commentid);
                if (!StringUtils.isEmpty(dianzan)) {
                    //点赞
                    toMap.put("pldianzan", 1);
                } else {
                    //未查询到记录  未点赞
                    toMap.put("pldianzan", 2);
                }
            } else {
                toMap.put("pldianzan", 2);
            }
            //判断用户是否登录
            if (!isNull(request.getHeader(client_toke))) {
                //获取最新数据
                Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(client_toke));
                //获取当前登录用户的user对象
                user = appUserService.get(userId);
                flag = true;
            }
            //判断数据是否为空
            if (huifuList != null && huifuList.size() > 0) {
                //遍历动态list
                for (AppCommentReply comment : huifuList) {
                    //信息转移Dto
                    CommentReplyDto cd = new CommentReplyDto();
                    BeanUtils.copyProperties(comment, cd);

                    list.add(cd);
                }
                toMap.put("list", list);
                return this.sucessPage(toMap, splitPage.getNextPageNo());
            } else {
                toMap.put("list", list);
                return this.sucessPage(toMap, -1);
            }
        } catch (Exception e) {
            return this.errorJSON("The system is busy,please try again later");
        }
    }


    /**
     * 动态转发记录
     *
     * @Param: [id 动态id]
     * @return: com.vf.admin.common.entity.Result
     * @Author: zhouyunyi
     * @Date: 2021/07/29
     * @Time: 11:52
     */
    @RequestMapping("/zhuanfa")
    @ResponseBody
    public Result zhuanfa(Integer id) {
        try {
            if (StringEx.isNull(id)) {
                return this.errorJSON("No dynamic information");
            }
            AppDynamic appDynamic = appDynamicService.getByid(id);
            if (appDynamic == null) {
                return this.errorJSON("The dynamic does not exist");
            }
            //变更动态转发数量
            appDynamicService.zhuanfaUpdate(id);
            return this.sucessJSON("成功");
        } catch (Exception e) {
            return this.errorJSON("The system is busy,please try again later");
        }
    }

    @RequestMapping("/dynamicPic")
    @ResponseBody
    public Result dynamicPic(@RequestParam(value = "userId") Integer userId) {
        if (userId == null) {
            userId = getUserId();
        }
        List<String> list = appDynamicService.myDynamicPic(userId);

        return this.sucessJSON(list);
    }

    /**
     * 动态通知
     *
     * @param pageno
     * @return
     */
    /*@RequestMapping("/dynamicAlert")
    @ResponseBody
    public Result dynamicAlert(Integer pageno) {
        Integer userId = getUserId();
        redisUtil.del(String.format(RedisKeys.USER_BADGE, userId));

        SplitPageBean splitPageBean = new SplitPageBean(pageno, 10);
        //先查询我发出的动态
        List<AppDynamic> dynamicList = appDynamicService.specificUserList(userId, splitPageBean);
        List<DynamicAlertDto> list = new ArrayList<>();

        for (AppDynamic dynamic : dynamicList) {
            DynamicAlertDto dd = new DynamicAlertDto();
            BeanUtils.copyProperties(dynamic, dd);

            if(org.apache.commons.lang3.StringUtils.isNotBlank(dd.getImage())) {
                String[] split = dd.getImage().split(",");
                dd.setImage(split[0]);
            }
            List<AppDynamicDianzan> dianzanList = appDynamicDianzanService.count(dynamic.getId());
            List<AppComment> commentList = appCommentService.listByDynamicId(dynamic.getId());
            //我的动态评论和点赞信息
            if (dianzanList.size() != 0 && commentList.size() != 0) {
                //是否有我发出的评论
                List<AppComment> myComments = commentList.stream().filter(e -> e.getUserid() == userId).collect(Collectors.toList());
                for (AppComment comment : myComments) {
                    //我的评论是否有点赞和回复信息
                    List<AppCommentDianzan> commentDianzanList = appCommentDianzanService.getByCommentId(comment.getId());
                    List<AppCommentReply> commentReplyList = appCommentReplyService.hfcount(comment.getId());

                    comment.setCommentDianzanList(commentDianzanList);
                    comment.setCommentReplyList(commentReplyList);
                }

                dd.setDianzanList(dianzanList);
                dd.setCommentList(commentList);
                list.add(dd);
            }
        }
        return sucessJSON(list);
    }*/
}
